package com.thread.thread.ThreadPool线程池;

import sun.applet.Main;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
//ForkJoinPool(将一个任务拆分成多个任务去执行) 可以继承RecursiveTask（适合有返回值）也可以继承RecursivAction(适合没有返回值)，
// 此处测试的为1+到10，6这个分界值是随意添加的
public class ForkJoinPoolTest {
	ForkJoinPool forkJoinPool = new ForkJoinPool(4);

	 class Sum extends RecursiveTask {
		public List<Integer> list;

		public Sum() {
		}

		public Sum(List list) {
			this.list = list;
		}

		@Override
		protected Integer compute() {
			int n=list.size();
			if(n>6){
				Sum left=new Sum(list.subList(0,6));
				Sum right=new Sum(list.subList(6,n));
				Future<Integer> future1= forkJoinPool.submit(left);
				Future<Integer> future2=forkJoinPool.submit(right);
				int result=0;
				try {
					result=future1.get()+future2.get();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				return result;
			}else{
				int sum=0;
				for(int i=0;i<list.size();i++){
					sum+=list.get(i);
				}
				return sum;
			}

		}
	}

	public static void main(String[] args) {
		List<Integer> integers=new ArrayList<>();
		integers.add(1);
		integers.add(2);
		integers.add(3);
		integers.add(4);
		integers.add(5);
		integers.add(6);
		integers.add(7);
		integers.add(8);
		integers.add(9);
		integers.add(10);
		ForkJoinPoolTest sum=new ForkJoinPoolTest();

		System.out.println("多线程执行结果："+sum.getSum(integers));

	}

	public int getSum(List list){
		Sum sum=new  Sum(list);
		ForkJoinPool pool = ForkJoinPool.commonPool();
		Future<Integer> future = pool.submit(sum); //提交分解的SumTask 任务
		int result=0;
		try {
			result=future.get();
			return result;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		return result;
	}
}
